package cn.tedu.ivoscm.dict.service.impl;

import cn.tedu.ivoscm.base.exception.ServiceException;
import cn.tedu.ivoscm.base.response.StatusCode;
import cn.tedu.ivoscm.dict.mapper.DictMapper;
import cn.tedu.ivoscm.dict.pojo.dto.DictQuery;
import cn.tedu.ivoscm.dict.pojo.dto.DictSaveParam;
import cn.tedu.ivoscm.dict.pojo.entity.Dict;
import cn.tedu.ivoscm.dict.pojo.vo.DictVO;
import cn.tedu.ivoscm.dict.service.DictService;
import cn.tedu.ivoscm.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.ivoscm.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.ivoscm.dictoption.service.impl.DictOptionServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictServiceImpl implements DictService {
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private DictOptionServiceImpl dictOptionService;

    @Override
    public List<DictVO> select(DictQuery dq) {
        log.debug("查询字典列表业务：{}", dq);
        List<DictVO> list = dictMapper.select(dq);
        return list;
    }

    @Override
    public void save(DictSaveParam dsp) {
        log.debug("保存字典业务：{}", dsp);
        Dict d = new Dict();
        BeanUtils.copyProperties(dsp, d);
        if(d.getId() == null){
            d.setCreateTime(new Date());
            dictMapper.insert(d);
        } else {
            d.setUpdateTime(new Date());
            dictMapper.update(d);
        }
    }

    @Override
    @Transactional  // 该注解用于事务控制，让所有数据库操作全部在一个事务中执行，只要任意SQL语句出错，都将回滚事务，不会对数据库造成任何影响
    public void deleteById(Long id) {
        log.debug("删除字典业务：{}", id);
        DictOptionQuery dq = new DictOptionQuery();
        dq.setDictId(id);
        List<DictOptionVO> list = dictOptionService.select(dq);
        if(!list.isEmpty()){
            // 由于字典项和字典并非物理上实际存在的对应关系，因此删除字典可以直接把所有的字典项也删掉，而不用考虑字典项是否被引用，也就不必跑出异常
//            throw new ServiceException(StatusCode.DICT_OPTIONS_DEPLOYED);
            dictOptionService.deleteByDictId(id);
        }
        dictMapper.deleteById(id);
    }
}
